﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EntityFrameworks.Entity.Core;
namespace Common.Background.Controllers
{
    using EntityFrameworks.Data.Core;
    using System.Text;
    using Common.Background.Helper;
    using EntityFrameworks.Entity.Core.CommonEnums;

    [Common.Background.Filter.AuthorizationFilter]
    public partial class MenuController : BaseController
    {
        #region Fields
        /// <summary>
        /// 菜单列表
        /// </summary>
        static readonly List<WebManageMenus> WebManageMenus;
        readonly List<WebManageMenus> _currentMenuList = new List<WebManageMenus>();
        #endregion

        #region Constructors
        static MenuController()
        {
            WebManageMenus = new BackgroundBase<WebManageMenus>().GetModel().ToList();
        }
        public MenuController()
            : base(new backgroundEntities())
        {
            _currentMenuList = new List<WebManageMenus>();
            var roleList = UserRepository.GetModel()
                                         .Where(i => i.ManageUserID == CurrentUserId)
                                         .Include(i => i.WebManageRoles)
                                         .Select(i => i.WebManageRoles)
                                         .ToList();
            roleList.ForEach(k =>
            {
                k.ToList().ForEach(kk => RoleRepository.GetModel().Include(kkk => kkk.WebManageMenus)
                    .Where(j => j.ManageRoleID == kk.ManageRoleID)
                    .Select(m => m.WebManageMenus)
                    .ToList()
                    .ForEach(oo => oo.ToList().ForEach(j =>
                    {
                        if (!_currentMenuList.Contains(j))
                            _currentMenuList.Add(j);
                    })));
            });


        }
        #endregion

        /// <summary>
        /// 根ID，默认为第一个菜单ID
        /// </summary>
        static int MenuRoot
        {
            get
            {
                return WebManageMenus.FirstOrDefault(i => i.MenuLevel == 0) == null
                    ? 1
                    : WebManageMenus.FirstOrDefault(i => i.MenuLevel == 0).ID;
            }
        }

        #region 菜单管理
        [Common.Background.Filter.AuthorizationFilter]
        public ActionResult Index(int? page)
        {
            return View(MenuRepository.GetModel()
                                      .Include(i => i.WebManageRoles)
                                      .Where(i => i.Status != (int)Status.Deleted)
                                      .OrderBy(i => i.SortNumber)
                                      .ToPagedList(page ?? 1, base.PageSize));
        }
        [Common.Background.Filter.AuthorizationFilter]
        public ActionResult Create(int? id)
        {
            return View();
        }
        [Common.Background.Filter.AuthorizationFilter]
        [HttpPost]
        public ActionResult Create(WebManageMenus entity)
        {
            var parent = MenuRepository.Find(entity.ParentID);
            entity.MenuLevel = parent.MenuLevel + 1;
            entity.UpdateDate = DateTime.Now;
            entity.Operator = string.Empty;
            entity.Status = Status.Normal.GetHashCode();
            if (ModelState.IsValid)
            {
                try
                {
                    MenuRepository.Insert(entity);

                    return RedirectToAction("Index");
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "请认真填写表单" + ex.Message);
                }
            }
            return View();
        }
        [Common.Background.Filter.AuthorizationFilter]
        public ActionResult Edit(int id)
        {
            ViewBag.RoleList = RoleRepository.GetModel().ToList();
            return View(MenuRepository.Find(id));
        }
        [Common.Background.Filter.AuthorizationFilter]
        [HttpPost]
        public ActionResult Edit(WebManageMenus entity)
        {
            var entitynew = MenuRepository.Find(entity.MenuID);

            try
            {
                entitynew.MenuID = entity.MenuID;
                entitynew.MenuName = entity.MenuName;
                entitynew.MenuLevel = entity.MenuLevel;
                entitynew.LinkUrl = entity.LinkUrl ?? string.Empty;
                entitynew.About = entity.About ?? string.Empty;
                entitynew.Operator = string.Empty;
                entitynew.ParentID = entity.ParentID;
                entitynew.SortNumber = entity.SortNumber;
                entitynew.Status = Status.Normal.GetHashCode();
                MenuRepository.Update(entitynew);

                return RedirectToAction("Index");
            }
            catch
            {
                throw;
            }
        }
        [Common.Background.Filter.AuthorizationFilter]
        public ActionResult Delete(int id)
        {
            try
            {
                MenuRepository.Update<WebManageMenus>(i => new WebManageMenus
                {
                    MenuID = id,
                    Status = Status.Deleted.GetHashCode()
                });
                return RedirectToAction("Index");
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 左侧与顶部菜单
        /// <summary>
        /// 左侧菜单
        /// </summary>
        /// <returns></returns>
        public ContentResult LeftMenuTree()
        {
            int menuId;
            if (!int.TryParse((Session["MenuID"] ?? string.Empty).ToString(), out menuId))
                menuId = MenuRoot;

            menuId = menuId == 0 ? MenuRoot : menuId;
            var html = new StringBuilder();

            html.Append("<ul>");
            CreateLeftTree(_currentMenuList.First(i => i.MenuID == menuId), html);
            html.Append("</ul>");

            return Content(html.ToString());
        }
        /// <summary>
        /// 构建左侧菜单树
        /// </summary>
        /// <param name="tree"></param>
        /// <param name="html"></param>
        private void CreateLeftTree(WebManageMenus tree, StringBuilder html)
        {

            html.Append("<li class='level" + tree.Level + "'>");
            html.AppendFormat("<a href='{0}'>{1}</a>"
                , tree.LinkUrl
                , tree.MenuName);
            var childmanagemenus = _currentMenuList.Where(i => i.ParentID == tree.MenuID);
            #region 子树加载
            if (childmanagemenus != null && childmanagemenus.Count() > 0)//如果子树，加加载这块
            {
                html.Append("<ul  style='margin:0px;padding:0'>");
                foreach (var item in childmanagemenus)
                {
                    this.CreateLeftTree(item, html);
                }
                html.Append("</ul>");
            }
            #endregion
            html.Append("</li>");
        }
        /// <summary>
        /// 顶部菜单
        /// </summary>
        /// <returns></returns>
        public PartialViewResult TopMenuTree()
        {
            var menuList = _currentMenuList.Where(i => i.MenuLevel == 1).ToList();

            return PartialView(menuList);
        }
        /// <summary>
        /// 存储当前一级菜单
        /// </summary>
        /// <param name="menuId"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult SaveMenu(int menuId, string returnUrl)
        {
            Session["MenuID"] = menuId;
            return Redirect(returnUrl);
        }

        public void LeftMenuStatus(int flag)
        {
            Session.Add("LeftMenuStatus", flag);
        }
        #endregion

    }
}
